package com.example.service.util.utils;

import com.example.common.util.constant.CommonUtilConstants;
import com.example.common.util.enums.BusinessEnum;
import com.example.common.util.exception.BusinessException;
import com.example.common.util.utils.StringUtils;
import com.example.service.util.properties.*;
import io.jsonwebtoken.*;

/**
 * @Author juzipi
 * @Date 2021/7/16 10:49
 * @Info
 */
public class JwtUtils {



    public static String createToken(Long userId, String userName,String secretKey){
        String token = Jwts.builder()
                .setSubject(CommonUtilConstants.JWT_SUBJECT)
                .claim(CommonUtilConstants.JWT_CLAIM_USER_ID, userId)
                .claim(CommonUtilConstants.JWT_CLAIM_USER_NAME, userName)
                .signWith(SignatureAlgorithm.HS256, secretKey)
                .compressWith(CompressionCodecs.GZIP)//压缩？
                .compact();
        return token;
    }


    //根据token字符串得到用户id
    public static Long getUserId(String token) {
        if (StringUtils.isNotEmpty(token)){
            Jws<Claims> claimsJws = Jwts.parser().setSigningKey(UserPropertiesVariable.secret).parseClaimsJws(token);
            Claims claims = claimsJws.getBody();
            Integer userId = (Integer)claims.get(CommonUtilConstants.JWT_CLAIM_USER_ID);
            return userId.longValue();
        }
        throw new BusinessException(BusinessEnum.TOKEN_ERROR);
    }

    //根据token字符串得到用户名称
    public static String getUserName(String token) {
        if(StringUtils.isEmpty(token)){
            Jws<Claims> claimsJws = Jwts.parser().setSigningKey(UserPropertiesVariable.secret).parseClaimsJws(token);
            Claims claims = claimsJws.getBody();
            return (String)claims.get(CommonUtilConstants.JWT_CLAIM_USER_NAME);
        }
        throw new BusinessException(BusinessEnum.TOKEN_ERROR);
    }



}
